package com.slife.serial.utils;

import java.math.BigInteger;

public class HexUtils {

    public static String addZeroForNum(String str,int strLength) {
        int strLen =str.length();
        if (strLen <strLength) {
            while (strLen< strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append("0").append(str);//左补0
                //  sb.append(str).append("0");//右补0
                str= sb.toString();
                strLen= str.length();
            }
        }
        return str;
    }
    /**
     * byte数组转hex
     * @param bytes
     * @return
     */
    public static String byteToHex(byte[] bytes){
        String strHex = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < bytes.length; n++) {
            strHex = Integer.toHexString(bytes[n] & 0xFF);
            sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示，位数不够，高位补0
        }
        return sb.toString().trim();
    }


    /**
     * 十进制转16进制字符串
     * @param hex
     * @return
     */
    public static String integerToHex(String hex){
        BigInteger bigInt = new BigInteger(hex, 10);
        return bigInt.toString(16);
    }
    /**
     * hex转byte数组
     * @param hex
     * @return
     */
    public static byte[] hexToByte(String hex){
        int m = 0, n = 0;
        int byteLen = hex.length() / 2; // 每两个字符描述一个字节
        byte[] ret = new byte[byteLen];
        for (int i = 0; i < byteLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
            ret[i] = Byte.valueOf((byte)intVal);
        }
        return ret;
    }

    public static Float hexToFloat(String hex){

        Long l = Long.parseLong(hex, 16);
        return Float.intBitsToFloat(l.intValue());
    }

}
